<template>
  <!-- 拆分 -->
  <el-dialog
    title="批量添加"
    width="70%"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    :visible="batchVisible"
    @close="close"
    @open="open"
    class="main_dialog"
  >
    <el-form :inline="true" ref="batchFrom" :model="form">
      <el-form-item prop="category_ids">
        <el-cascader
          class="wid220"
          :value="form.category_ids"
          :props="props"
          :options="options"
          clearable
          collapse-tags
          @change="changeCasader"
          placeholder="全部分类"
        ></el-cascader>
      </el-form-item>
      <el-form-item prop="name">
        <el-input v-model="form.name" clearable  @input="changeName" placeholder="请输入商品名称/编码" class="wid220"></el-input>
      </el-form-item>
      <el-form-item prop="status">
        <el-radio-group v-model="form.status" @change="getData">
          <el-radio :label="-1">全部</el-radio>
          <el-radio :label="1">上架</el-radio>
          <el-radio :label="0">下架</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <MainTable
      ref="batchTable"
      :loading="tableLoading"
      :columns="batchColumns"
      :tableData="tableData"
      :enableHeaderDrag="false"
      :height="450"
      @select="handleSelect"
      @select-all="handleSelectionChange"
      class="revocation"
    >
      <template #customLeft>
        <el-table-column width="50" type="selection" />
      </template>
      <template #spu_name="{ row }">
        <span>{{ row.spu_name.title }}</span>
      </template>
      <template #spu_unit="{ row }">
        <span>{{ row.spu_unit.title }}</span>
      </template>
      <template #goods_status="{ row }">
        <el-tag :type="row.goods_status == 1 ? 'success' : 'info'">
          {{ row.goods_status == 1 ? "上架" : "下架" }}
        </el-tag>
      </template>
      <template #status="{ row }">
        {{ row.status == 1 ? "开" : "关" }}
      </template>
    </MainTable>
    <div class="flex-btw mg-t-10">
      <div></div>
      <MainPagination
        background
        :total="totalCount"
        :page-size="current.size"
        :current-page="current.page"
        @size-change="changeSize"
        @current-change="changePage"
        :page-sizes="[10, 20, 30, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
      />
    </div>
    <div slot="footer" class="dialog-footer">
      <el-button @click="close">取 消</el-button>
      <el-button type="primary" @click="submit" v-repeatClick>确 定</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { batchColumns } from "./mockData.js";
import { goodsGetGoodsSpuList } from "@/api/order/orderList";
import { getPriceListSpuIds } from "@/api/currency";
import { debounce } from 'lodash';
import { mapGetters } from "vuex";
import { packApi } from "@/utils/public";
export default {
  props: {
    batchVisible: {
      type: Boolean,
      default: false,
    },
    uid: {
      type: [Number, String],
      default: 0,
    },
    group_id: {
      type: [Number, String],
      default: 0,
    },
    send_time: {
      type: String,
      default: "",
    },
    options: {
      type: Array,
      default: ()=> [],
    },
    selectList: {
      type: Array,
      default: ()=> [],
    },
  },
  computed: {
    ...mapGetters(["avatar"]),
    // 将 selectList 转换为一个 Set，使用 goods_spu_id 作为唯一标识
    selectedGoodsIds({ selectList }) {
      return new Set(selectList.map(item => item.goods_spu_id));
    },
  },
  data() {
    return {
      // 表格
      tableData: [],
      batchColumns, // 表格列
      tableLoading: false,
      // 表单
      form: {
        name: null,
        category_ids: null,
        status: -1,
      },
      // 分页
      current: {
        page: 1,
        size: 20,
      },
      totalCount: 1,
      // 商品分类树的格式
      props: {
        multiple: true,
        value: "id",
        label: "title",
        children: "selfNext",
      },
    };
  },
  methods: {
    // 获取数据
    getData() {
      this.tableLoading = true;
      let data = packApi({
        ...this.form,
        ...this.current
      });
      goodsGetGoodsSpuList(data).then(res=> {
        this.tableLoading = false;
        if(res.errcode == 0) {
          this.totalCount = res.data.count;
          this.tableData = res.data.list;
          this.$nextTick(()=> {
            this.tableData.forEach(item=> {
              // 如果 item.id 在 selectedGoodsIds 中，则设置选中
              if(this.selectedGoodsIds.has(item.id)) {
                this.$refs.batchTable.tableRef().toggleRowSelection(item, true);
              }
            });
          });
        } else {
          this.$message.error(res.errmsg);
        }
      })
    },
    // dialog打开的回调
    open() {
      this.getData();
    },
    // 取消/关闭
    close() {
      this.resetData();
      this.$emit("update:batchVisible", false);
      this.$emit("close");
    },
    // 确定
    submit() {
      this.$emit("update:batchVisible", false);
      this.$emit("submit");
    },
    // 重置data数据
    resetData() {
      // this.$refs.batchFrom.resetFields();
      this.tableData = [];
      this.current = {
        page: 1,
        size: 20
      }
      this.totalCount = 1;
    },
    // 全选
    async handleSelectionChange(selection, e) {
      // 如果 selection 有长度，说明是全选就添加
      const state = selection.length ? "push" : "splice";
      this.tableLoading = true;
      let priceListId = this.tableData.map(item=> item.id).join(",");
      let Goodsprice = {};
      // 如果是新增才请求接口
      if(state === "push") Goodsprice = await this.getGoodsPrice(priceListId); // 价格
      let list_index = this.selectList.length;
      this.tableData.forEach(item => {
        if(!this.selectedGoodsIds.has(item.id) && state === "push") {
          ++list_index;
          item.list_index = list_index;
          let obj = this.buildParentData(item, Goodsprice, state);
          this.$emit("addShopData", obj);
        } else if(state === "splice") {
          let obj = this.buildParentData(item, Goodsprice, state);
          this.$emit("addShopData", obj);
        }
      });
      this.tableLoading = false;
    },
    // 单选
    async handleSelect(selection, row) {
      const state = this.selectedGoodsIds.has(row.id) ? "splice" : "push";
      this.tableLoading = true;
      let Goodsprice = {};
      // 如果是新增才请求接口
      if(state === "push") Goodsprice = await this.getGoodsPrice(row.id); // 价格
      row.list_index = this.selectList.length + 1;
      const obj = this.buildParentData(row, Goodsprice, state);
      this.$emit("addShopData", obj);
      this.tableLoading = false;
    },
    // 构建父组件数据
    buildParentData(row, Goodsprice, state) {
      const goodsRowPrice = Goodsprice[row.id] || {};
      let data = {
        list : {
          list_index: row.list_index,
          standard_goods_id: row.standard_goods_id,
          pid: row.pid,
          byname: row.byname,
          category_id: row.category_id,
          // spu_id: row.id, 
          cycle_id: goodsRowPrice.cycle_id,
          url: this.avatar.domain + row.pic || null,
          name: row.name,
          goods_id: row.goods_id,
          goods_spu_id: row.id,
          standard_spu_id: row.standard_spu_id,
          standard_spu_code: row.standard_spu_code,
          pic: row.pic,
          discount: row.discount,
          spu_name: row.spu_name.title,
          describe: row.describe,
          unit: row.spu_unit.title,
          inventory_num: row.inventory_num || 0,
          minimum: row.minimum,
          designated_inventory: row.designated_inventory,
          purchase_price: row.purchase_price || 0,
          order_num: row.order_num || 1,
          pre_price: goodsRowPrice.pre_price || 0,
          pre_purchase_price: goodsRowPrice.pre_purchase_price,
          order_price: goodsRowPrice.price || 0,
          remark: goodsRowPrice.remark,
          red: parseFloat(row.purchase_price) > parseFloat(goodsRowPrice.price)
        },
        state: state,
      }
      return data;
    },
    // 重置数据
    async getGoodsPrice(id) {
      let data = packApi({
        uid: this.uid,
        group_id: this.group_id,
        goods_spu_id: id,
        send_time: this.send_time,
      });
      const res = await getPriceListSpuIds(data);
      if(res.errcode == 0) {
        return res.data;
      } else {
        this.$message.error(res.errmsg);
      }
    },
    // 分类树修改事件
    changeCasader(e) {
      this.form.category_ids = e.map((item) => item.at(-1)).join(",");
      this.getData();
    },
    // 商品名称输入事件
    changeName: debounce(function () {
      this.getData();
    }, 1500),
    // 分页
    changeSize(pageSize) {
      this.current.size = pageSize;
      this.getData();
    },
    changePage(page) {
      this.current.page = page;
      this.getData();
    },
  },
};
</script>

<style lang="scss" scoped>
/deep/.main_table .el-table--small td.el-table__cell .cell {
  line-height: normal !important;
}
</style>